package com.szgr.baoyin.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.BuyProtectListAdapter;
import com.szgr.baoyin.adapter.RegisterListAdapter;
import com.szgr.baoyin.model.AddressProtect;
import com.szgr.baoyin.model.DetailConfig;
import com.szgr.baoyin.model.Goods;
import com.szgr.baoyin.model.OrderMember;
import com.szgr.baoyin.model.ProtectAddress;
import com.szgr.baoyin.model.ProtectGoods;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 购买维保
 */
public class BuyProtectActivity extends BaseActivity implements TextWatcher, CompoundButton.OnCheckedChangeListener {

    private Dialog dialog;
    private TextView tv_address;
    private View tipMessage;
    private TextView tv_tipAdd;
    private TextView tv_company;
    private TextView tv_faren;
    private TextView tv_farenPhone;
    private TextView tv_shengchan;
    private TextView tv_shengchanPhone;
    private TextView tv_jishu;
    private TextView tv_jishuPhone;
    private List<Goods> data;
    private LinearLayout menuView;
    private WheelView wheelView;
    private Dialog menuDialog;
    private int index = 1;
    private TextView tv_price;
    private TextView tv_type;
    private int protectNum = 1;
    private EditText et_num;
    private Goods selectedGoods;
    private TextView tv_allMoney;
    private TextView tv_allMoneyTip;
    private TextView tv_reduce;
    private TextView tv_reduceTip;
    private DecimalFormat format;
    private CheckBox cb_agree;
    private Button btn_send;
    private ArrayList<ProtectGoods> dataPro;
    private AddressProtect addressProtect;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 555:
                    HashMap<String,String> hashMap = (HashMap<String, String>) msg.obj;
                    Intent intent = new Intent(BuyProtectActivity.this,BuyProtectDetailActivity.class);
                    intent.putExtra("hashMap",hashMap);
                    intent.putExtra("dataPro",dataPro);
                    intent.putExtra("address",protectAddress);
                    startActivity(intent);
                    break;
                case 454:
                    protectAddress = proAddes.get(0);
                    tv_company.setText(protectAddress.getGsmc());
                    tv_address.setText(protectAddress.getArea_info() + protectAddress.getAddress());
                    tv_faren.setText(protectAddress.getGsfzr());
                    tv_farenPhone.setText(protectAddress.getGsfzr_tel());
                    tv_jishu.setText(protectAddress.getJsfzr());
                    tv_jishuPhone.setText(protectAddress.getJsfzr_tel());
                    addressId = protectAddress.getAddress_id();
                    break;
            }
        }
    };
    private String addressId;
    private ProtectAddress protectAddress;
    private List<ProtectAddress> proAddes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("购买维保");
    }

    @Override
    public void initView() {
        format = new DecimalFormat("0.00");
//        NoScrollListView lv_buyProtect = (NoScrollListView) findViewById(R.id.buy_protect_list_view);
//        lv_buyProtect.setAdapter(new BuyProtectListAdapter(this));
//        NoScrollListView lv_register = (NoScrollListView) findViewById(R.id.register_list_view);
//        lv_register.setAdapter(new RegisterListAdapter(this));

        btn_send = (Button) findViewById(R.id.buy_now);
        btn_send.setOnClickListener(this);
        findViewById(R.id.buy_protect_rule).setOnClickListener(this);
        tv_address = (TextView) findViewById(R.id.buy_protect_address);
        tv_address.setOnClickListener(this);
        tv_tipAdd = (TextView) findViewById(R.id.show_or_hidden);
        tv_tipAdd.setOnClickListener(this);
        tipMessage = findViewById(R.id.register_tip_message);

        tv_company = (TextView) findViewById(R.id.buy_protect_company);
        tv_faren = (TextView) findViewById(R.id.buy_protect_faren);
        tv_farenPhone = (TextView) findViewById(R.id.buy_protect_faren_phone);
        tv_shengchan = (TextView) findViewById(R.id.buy_protect_changzhang);
        tv_shengchanPhone = (TextView) findViewById(R.id.buy_protect_changzhang_phone);
        tv_jishu = (TextView) findViewById(R.id.buy_protect_tech);
        tv_jishuPhone = (TextView) findViewById(R.id.buy_protect_tech_phone);

        tv_company.setOnClickListener(this);
        tv_faren.setOnClickListener(this);
        tv_farenPhone.setOnClickListener(this);
        tv_jishu.setOnClickListener(this);
        tv_jishuPhone.setOnClickListener(this);

        tv_type = (TextView) findViewById(R.id.buy_protect_choose_type);
        tv_price = (TextView) findViewById(R.id.buy_protect_price);
        findViewById(R.id.protect_minus).setOnClickListener(this);
        et_num = (EditText) findViewById(R.id.protect_count);
        et_num.addTextChangedListener(this);
        findViewById(R.id.protect_add).setOnClickListener(this);
        tv_allMoney = (TextView) findViewById(R.id.buy_protect_all_money);
        tv_allMoneyTip = (TextView) findViewById(R.id.buy_protect_all_money_tip);
        tv_reduce = (TextView) findViewById(R.id.buy_protect_reduce);
        tv_reduceTip = (TextView) findViewById(R.id.buy_protect_reduce_tip);
        cb_agree = (CheckBox) findViewById(R.id.buy_protect_agree);
        cb_agree.setOnCheckedChangeListener(this);
        findViewById(R.id.buy_protect_vip).setOnClickListener(this);
        tv_type.setOnClickListener(this);

//        getProtectType();
        initDialog("选择型号", 0);
        getProtectQuery();

        getAddress();
    }

    private void getAddress() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_PROTECT_ADDRESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get address--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray address_list = datas.getJSONArray("address_list");
                            Gson gson = new Gson();
                            proAddes = gson.fromJson(address_list.toString(),new TypeToken<List<ProtectAddress>>(){}.getType());
                            if(proAddes.size() == 0){
                                mHandler.obtainMessage(453).sendToTarget();
                            }else{
                                mHandler.obtainMessage(454).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void getProtectQuery() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_PROTECT_QUERY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray goods_list = datas.getJSONArray("goods_list");
                            Gson gson = new Gson();
                            data = gson.fromJson(goods_list.toString(),new TypeToken<List<Goods>>(){}.getType());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 购买维保规格
     */
    private void getProtectType() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_PROTECT_TYPE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----buy protect---->" + s);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("goods_commonid","1581");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.buy_now:
                if(addressId == null || "".equals(addressId)){
                    ToastUtils.showToast("请选择维保地址");
                    return;
                }
                if(selectedGoods == null){
                    ToastUtils.showToast("请选择维保产品");
                    return;
                }
                buyStep1();
                break;
            case R.id.buy_protect_rule:
                Intent ruleIntent = new Intent(this, ProtectRuleActivity.class);
                ruleIntent.putExtra("fromBuy",true);
                startActivity(ruleIntent);
                break;
            case R.id.buy_protect_address:
            case R.id.buy_protect_company:
            case R.id.buy_protect_faren:
            case R.id.buy_protect_faren_phone:
            case R.id.buy_protect_tech:
            case R.id.buy_protect_tech_phone:
                startActivityForResult(new Intent(this,ProtectAddressActivity.class), 208);
                break;
            case R.id.show_or_hidden:
                if(tipMessage.getVisibility() == View.VISIBLE){
                    tipMessage.setVisibility(View.GONE);
                    tv_tipAdd.setText("+");
                }else if(tipMessage.getVisibility() == View.GONE){
                    tipMessage.setVisibility(View.VISIBLE);
                    tv_tipAdd.setText("—");
                }
                break;
            case R.id.buy_protect_choose_type:
                if(data != null && data.size() > 0){
                    List<String> strings = new ArrayList<>();
                    for (Goods g : data) {
                        strings.add(g.getGoods_name());
                    }
                    wheelView.setItems(strings);
                    wheelView.setSeletion(0);
                    menuDialog.show();
                }
                break;
            case R.id.buy_protect_vip:

                break;
            case R.id.protect_minus:
                if(protectNum > 1){
                    protectNum --;
                    et_num.setText(protectNum + "");
                    calculatePrice();
                }
                break;
            case R.id.protect_add:
                protectNum ++ ;
                et_num.setText(protectNum + "");
                calculatePrice();
                break;
        }
    }

    /**
     * 购买的第一步
     */
    private void buyStep1() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_SUBMIT_ORDER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONObject store_cart_list = datas.getJSONObject("store_cart_list");
                            Iterator<String> keys = store_cart_list.keys();
                            while(keys.hasNext()){
                                JSONObject jsonObject1 = store_cart_list.getJSONObject(keys.next());
                                JSONArray goods_list = jsonObject1.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                dataPro = gson.fromJson(goods_list.toString(), new TypeToken<List<ProtectGoods>>() {
                                }.getType());

                                JSONObject address_info = datas.getJSONObject("address_info");
                                addressProtect = gson.fromJson(address_info.toString(), AddressProtect.class);

                                String vat_hash = datas.getString("vat_hash");
                                JSONObject offpay = datas.getJSONObject("offpay");
                                String offpay_hash = offpay.getString("offpay_hash");

                                HashMap<String,Object> hashMap = new HashMap<>();
                                hashMap.put("vat_hash",vat_hash);
                                hashMap.put("offpay_hash",offpay_hash);

                                JSONObject jsonObject11 = datas.optJSONObject("store_points_list");
                                Iterator<String> keys1 = jsonObject11.keys();
                                while(keys1.hasNext()){
                                    JSONObject jsonObject2 = jsonObject11.getJSONObject(keys1.next());
                                    OrderMember orderMember = gson.fromJson(jsonObject2.toString(), OrderMember.class);
                                    hashMap.put("orderMember",orderMember);
                                }

                                mHandler.obtainMessage(555,hashMap).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("cart_id",selectedGoods.getGoods_id() + "|" + protectNum);
                map.put("goods_is_service","01");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void calculatePrice() {
        if(selectedGoods != null){
            double goods_price = Double.parseDouble(selectedGoods.getGoods_price());
            double count = goods_price * protectNum;
            tv_allMoney.setText(format.format(count) + "");
            tv_reduce.setText(format.format(count) + "");
            judgeLevel(count);
        }
    }

    private void judgeLevel(double price) {
        String cardName = "";
        double reducePrice = 0;
        if(price >= 800000){
            cardName = "大客户卡";
            reducePrice = price * 0.81;
        }else if(price >= 400000){
            cardName = "钻石卡";
            reducePrice = price * 0.85;
        } else if(price >= 200000){
            cardName = "白金卡";
            reducePrice = price * 0.88;
        }else if(price >= 100000){
            cardName = "金卡";
            reducePrice = price * 0.91;
        }else if(price >= 50000){
            cardName = "银卡";
            reducePrice = price * 0.93;
        }else if(price >= 25000){
            cardName = "会员3卡";
            reducePrice = price * 0.95;
        }else if(price >= 12500){
            cardName = "会员2卡";
            reducePrice = price * 0.96;
        }else if(price >= 7500){
            cardName = "会员1卡";
            reducePrice = price * 0.97;
        }

        if(!"".equals(cardName)){
            tv_allMoneyTip.setText("(支付金额已达" + cardName + "级别)");
            tv_reduceTip.setText("(" + cardName + "折扣价)");
        }else{
            tv_allMoneyTip.setText("");
            tv_reduceTip.setText("");
        }

        if(reducePrice != 0){
            tv_reduce.setText(format.format(reducePrice) + "");
        }
    }

    public void initDialog(String title, final int position){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("---index : ---->" + index);
                selectedGoods = data.get(index - 1);
                tv_type.setText(selectedGoods.getGoods_name());
                tv_price.setText(selectedGoods.getGoods_price());
                calculatePrice();

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null){
            switch (resultCode){
                case 209:
                    protectAddress = (ProtectAddress) data.getSerializableExtra("address");
                    tv_company.setText(protectAddress.getGsmc());
                    tv_address.setText(protectAddress.getArea_info() + protectAddress.getAddress());
                    tv_faren.setText(protectAddress.getGsfzr());
                    tv_farenPhone.setText(protectAddress.getGsfzr_tel());
                    tv_jishu.setText(protectAddress.getJsfzr());
                    tv_jishuPhone.setText(protectAddress.getJsfzr_tel());
                    addressId = protectAddress.getAddress_id();
                    break;
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length() >= 1) {
            protectNum = Integer.parseInt(s.toString());
        }else{
            et_num.setText("1");
            protectNum = 1;
        }
        calculatePrice();
    }

    @Override
    public void afterTextChanged(Editable s) {
//        String string = s.toString();
//        et_num.setText(string);
//        protectNum = Integer.parseInt(string);
//        calculatePrice();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            btn_send.setEnabled(true);
        }else{
            btn_send.setEnabled(false);
        }
    }
}
